<template>
  <div class="kmSummary">
    <div class="clearfix searchBox">
      <div class="fl search">
        <quickSearch :advForm="quickSearchForm" @QuickSearch="searchFun"></quickSearch>
      </div>
      <div class="fr btn">
        <el-button size="mini" type="primary" @click="searchFun">查询</el-button>
        <el-button class="none" size="mini" @click="importDialog" v-functions="['knowledge_mgt_channel_1_import']">导入</el-button>
        <el-button size="mini" @click="exportDialog" v-functions="['knowledge_mgt_channel_1_export']">导出</el-button>
      </div>
    </div>
    <div class="knowledgeListBox">
      <knowledgeList :dirObj="currentDirObj"></knowledgeList>
    </div>
    <el-dialog
      title="导入知识库"
      :visible.sync="importVisible"
      width="30%">
      <div>
        <el-button size="mini" icon="el-icon-download" class="fl importBtn">
          <a href="/temp/km-Import.xlsx" download="km-import">下载导入模板</a>
        </el-button>
        <el-upload
          class="upload-demo"
          ref="epxortKm"
          accept=".xls, .xlsx"
          :action="kmUrl"
          :limit='1'
          :on-success="handleImportSuccess"
          :on-remove="handleRemove"
          :headers="{
            sessionid: accountObj.userId,
            loginToken: accountObj.loginToken
          }">
          <el-button size="mini" class="fl" style="marginLeft: 10px">导入Excel文件</el-button>
        </el-upload>
        <div class="instructions">
          <h5>说明：</h5>
          <ul>
            <li>1、支持后缀为xls何xlsx的excel文件导入；</li>
            <li>2、wps格式的文件导入成功率高，office低版本容易导入失败；</li>
            <li>3、支持一个文件一个工作表，多个工作表无法导入；</li>
            <li>4、单次最多导入1000条，超出1000条无法导入；</li>
            <li>5、模板表头不可修改，修改后无法导入；</li>
            <li>6、导入文件不可超出**M，超出后无法导入；</li>
            <li>7、导入时异步处理，提交导入后可以立刻进行其他的导入，服务器会排队处理，结果在【传输中心】查看；</li>
          </ul>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">取 消</el-button>
        <el-button type="primary" @click="importSave">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="导出知识库"
      :visible.sync="exportVisible"
      width="30%">
      <div class="exportDialog">
        <div class="exportTitle" v-if="checkHasAccess.canShow">导出目录</div>
        <el-cascader
          placeholder="请选择要导出的目录"
          v-model="categories"
          :props="{ checkStrictly: true, value: '_id', multiple: true }"
          :options="exportObj.options"
          @change="cascaderChange"
          clearable
          filterable
        >
        </el-cascader>
        <div class="exportTitle">导出目录</div>
        <el-radio v-model="exportObj.delTags" :label="false">携带网页标签样式</el-radio>
        <el-radio v-model="exportObj.delTags" :label="true">去除网页标签样式</el-radio>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import knowledgeList from '@/views/km/knowledgeBase/knowledgeList.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { deepClone } from '@/utils/common'
import { KmModule } from '@/store/modules/km/index'
import isEmpty from 'lodash/isEmpty'
import { knowledgeAccess } from '@/utils/kmAccess'
@Component({
  name: 'kmSummary',
  components: { knowledgeList, quickSearch }
})
export default class KmSummary extends Vue {
  private $bus: any
  private $message: any
  private $store: any
  private $router: any

  private agentList = []

  private quickSearchForm: any = {
    form: {
      keywordsType: 'all',
      keywords: '',
      updateUser: '',
      createUser: '',
      status: '',
      updateTime: []
    },
    advSearchOptions: []
  }

  private accountObj = {
    account: '',
    userId: '',
    loginToken: ''
  }

  private exportObj: any = {
    categories: [],
    delTags: false,
    options: []
  }

  private categories = []

  private importVisible = false

  private currentDirObj = {}

  private fileObj = {
    path: '',
    count: ''
  }

  private exportVisible = false

  get kmUrl () {
    return '/upload?accountId=' + this.accountObj.account + '&module=km'
  }

  get checkHasAccess () {
    return knowledgeAccess(this.$store.state.km.clickNode.node, this.$store.state.common.session)
  }

  private checkAccess (node: any) {
    return knowledgeAccess(node, this.$store.state.common.session)
  }

  private importDialog () {
    this.importVisible = true
  }

  private handleImportSuccess (res: any) {
    if (res && res.success) {
      this.fileObj.path = res.data.path
    }
  }

  private handleRemove () {
    this.fileObj.path = ''
  }

  private importSave () {
    if (!this.fileObj.path) {
      this.$message.error('请选择文件上传')
      return
    }
    const actionData = {
      url: '/im-km/import/action/importTask',
      method: 'post',
      data: {
        kmType: 'inner',
        filepath: this.fileObj.path
      }
    }
    const epxortRef: any = this.$refs.epxortKm
    epxortRef.clearFiles()
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('导入任务已经生成，请前往传输中心查看！')
        this.importVisible = false
      }
    })
  }

  private exportSave () {
    if (!this.exportObj.categories || (this.exportObj.categories && this.exportObj.categories.length === 0)) {
      this.$message.error('请选择目录进行导出')
      return
    }
    const { categories, delTags } = this.exportObj
    const actionData = {
      url: '/im-km/export/action/exportTask',
      method: 'post',
      data: {
        categories,
        delTags,
        kmType: 'inner'
      }
    }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
        this.exportVisible = false
        this.categories = []
      }
    })
  }

  private jumpToTransmissionCenter () {
    this.$router.push('/transmission_center/index/tx_export_task?taskModule=km')
  }

  private cascaderChange (val: any) {
    this.exportObj.categories = val
  }

  public deepDisable (list) {
    const each = (arr) => {
      arr.forEach(i => {
        const { canEdit, canShow } = this.checkAccess(i)
        i.disabled = !canEdit && !canShow
        if (!isEmpty(i.children)) {
          each(i.children)
        }
      })
    }
    each(list)
  }

  private exportDialog () {
    const actionData = { url: '/im-km/action/catalog/list', method: 'POST', data: { kmType: 'inner' } }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        const options = res.data.tree || [];
        this.deepDisable(options)
        this.exportObj.options = options
      }
    })
    this.exportVisible = true
  }

  private searchFun () {
    if (this.quickSearchForm.form.keywords) {
      this.$bus.$emit('keywordsSearchFun', this.quickSearchForm.form)
    } else {
      this.$bus.$emit('kmSearchFun', this.quickSearchForm.form)
    }
  }

  private clearSearchForm () {
    this.quickSearchForm.form = {
      keywordsType: 'all',
      keywords: '',
      updateUser: '',
      createUser: '',
      status: '',
      updateTime: []
    }
  }

  private mounted () {
    this.quickSearchForm.advSearchOptions = [
      {
        label: '关键字搜索',
        inputType: 'selectAndIpt',
        placeholder: '请输入要搜索的信息',
        name: 'keywordsType',
        searchName: 'keywords',
        selectData: [
          { name: '全部', _id: 'all' },
          { name: '标题', _id: 'title' },
          { name: '内容', _id: 'content' }
        ]
      },
      { label: '创建人', inputType: 'select', name: 'createUser', clearable: true, selectData: this.agentList },
      { label: '更新人', inputType: 'select', name: 'updateUser', clearable: true, selectData: this.agentList },
      {
        label: '知识状态',
        inputType: 'select',
        clearable: true,
        selectData: [
          { name: '全部', _id: '' },
          { name: '失效', _id: 'invalid' },
          { name: '有效', _id: 'valid' }
        ],
        name: 'status'
      },
      { label: '更新时间', inputType: 'dateTimeRange', clearable: true, name: 'updateTime' }
    ]
  }

  private beforeDestroy () {
    this.$bus.$off('directoryClick')
    this.$bus.$off('searchListBack')
    this.$bus.$off('addKnowledge')
  }

  private beforeMount () {
    this.$bus.$on('directoryClick', (nodeObj) => {
      this.currentDirObj = (nodeObj && nodeObj.data) || {}
      this.clearSearchForm()
    })
    this.$bus.$on('searchListBack', () => {
      this.clearSearchForm()
    })
    this.$bus.$on('addKnowledge', () => {
      this.clearSearchForm()
    })
    const agents = deepClone(this.$store.state.common.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ _id: agents[i]._id, name: agents[i].name })
    }
    this.agentList = agentsArr
    this.accountObj.account = (this.$store as any).state.common.session.account._id
    this.accountObj.userId = (this.$store as any).state.common.session.user._id
    this.accountObj.loginToken = (this.$store as any).state.common.session.user.loginToken
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/common/style/common.styl'
  .kmSummary
    height 100%
    .searchBox
      height 161px
      overflow auto
      border-bottom 1px solid $border-main
      .search
        width calc(100% - 200px)
      .btn
        margin-top 25px
    .knowledgeListBox
      height calc(100% - 170px)
  .importBtn
    a
      color #303753
  .importBtn:hover a
    color #008cee
  .instructions
    margin-top 22px
    h5
      font-size 12
    li
      padding 4px
      color #767E91
      font-size 12px
  .exportDialog .el-cascader
    width 100%
    margin-bottom 10px
  .exportTitle
    margin-bottom 10px
    color #303753
    font-size 12px
  .none
    display none
</style>
<style lang="stylus">
  .el-cascader-node__label
    max-width 200px
</style>
